1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect.testing;
18  
19  import com.google.common.annotations.GwtCompatible;
20  import com.google.common.collect.testing.features.CollectionSize;
21  
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.Collection;
25  import java.util.List;
26  
27  /**
28   * Generator for collection of a particular size.
29   *
30   * @author George van den Driessche
31   */
32  @GwtCompatible
33  public final class OneSizeGenerator<T, E>
34      implements OneSizeTestContainerGenerator<T, E> {
35    private final TestContainerGenerator<T, E> generator;
36    private final CollectionSize collectionSize;
37  
38    public OneSizeGenerator(TestContainerGenerator<T, E> generator,
39        CollectionSize collectionSize) {
40      this.generator = generator;
41      this.collectionSize = collectionSize;
42    }
43  
44    @Override
45    public TestContainerGenerator<T, E> getInnerGenerator() {
46      return generator;
47    }
48  
49    @Override
50    public SampleElements<E> samples() {
51      return generator.samples();
52    }
53  
54    @Override
55    public T create(Object... elements) {
56      return generator.create(elements);
57    }
58  
59    @Override
60    public E[] createArray(int length) {
61      return generator.createArray(length);
62    }
63  
64    @Override
65    public T createTestSubject() {
66      Collection<E> elements = getSampleElements(
67          getCollectionSize().getNumElements());
68      return generator.create(elements.toArray());
69    }
70  
71    @Override
72    public Collection<E> getSampleElements(int howMany) {
73      SampleElements<E> samples = samples();
74      @SuppressWarnings("unchecked")
75      List<E> allSampleElements = Arrays.asList(
76          samples.e0, samples.e1, samples.e2, samples.e3, samples.e4);
77      return new ArrayList<E>(allSampleElements.subList(0, howMany));
78    }
79  
80    @Override
81    public CollectionSize getCollectionSize() {
82      return collectionSize;
83    }
84  
85    @Override
86    public Iterable<E> order(List<E> insertionOrder) {
87      return generator.order(insertionOrder);
88    }
89  }